/******************************************************************************
 * Copyright (C) 671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef NODECPP_FOUNDATION_THREADINGPOLICY_H_
#define NODECPP_FOUNDATION_THREADINGPOLICY_H_

#include <NodeCpp/Macros.h>

namespace NodeCpp
{
    template<typename MUTEX>
    class GeneralLock
    {
    public:
        GeneralLock(MUTEX& _Mutex) : Mutex_(_Mutex) { Mutex_.Lock(); }
        ~GeneralLock(void) { Mutex_.Unlock(); }
    private:
        MUTEX& Mutex_;
        DISALLOW_COPY_AND_ASSIGN(GeneralLock);
    };

    template<class T>
    class SingleThreaded
    {
    public:
        struct Lock
        {
            Lock(void) { }
            Lock(const T&) { }
            Lock(const SingleThreaded<T>&) { }
        };
    };

    template<class T, class MUTEX>
    class ObjectLevelLockable
    {
    public:
        ObjectLevelLockable(void) : Mutex_() { }
        friend class Lock;

        class Lock
        {
        public:
            Lock(ObjectLevelLockable<T, MUTEX>& _Host) : Lock_(_Host.Mutex_) { }
        private:
            GeneralLock<MUTEX> Lock_;
        };

    private:
        MUTEX Mutex_;
        DISALLOW_COPY_AND_ASSIGN(ObjectLevelLockable);
    };

    template<class T, class MUTEX>
    class ClassLevelLockable
    {
    public:
        ClassLevelLockable(void) { }
        friend class Lock;
        class Lock
        {
        public:
            Lock(const T& /*host*/) { ClassLevelLockable<T, MUTEX>::Mutex_.Lock(); }
            Lock(const ClassLevelLockable<T, MUTEX>&) { ClassLevelLockable<T, MUTEX>::Mutex_.Lock(); }
            Lock(void) { ClassLevelLockable<T, MUTEX>::Mutex_.Lock(); }
            ~Lock(void) { ClassLevelLockable<T, MUTEX>::Mutex_.Unlock(); }
        };
    private:
        static MUTEX Mutex_;
    };
}
template<class T, class MUTEX> MUTEX NodeCpp::ClassLevelLockable<T, MUTEX>::Mutex_;

#define INSTANTIATE_CLASS_MUTEX(CTYPE, MUTEX) \
    template class NodeCpp::ClassLevelLockable<CTYPE, MUTEX>

#endif /* NODECPP_FOUNDATION_THREADINGPOLICY_H_ */
